<!--
 * @Author: 四川华西绿舍建材有限公司
 * @Date: 2024-03-21 16:37:55
 * @LastEditors: 陈波
 * @LastEditTime: 2024-04-25 17:08:11
 * @Description: 
 * @FilePath: \graDesign\src\views\DataMock\index.vue
-->
<template>
  <div>
    <LayoutIndex>
      <div class="flex_between_wrap">
        <div class="flex_between">
          <el-input
            v-model="deviceNum"
            type="number"
            min='1'
            max='100'
            style="min-width: 350px"
            placeholder="Please input Device Number"
          >
            <template #prepend>设备数量：</template>
          </el-input>
          <el-button
            style="margin-left: 20px;"
            type="primary"
            plain 
            @click="generateData()"
          >生成模拟器</el-button>
        </div>
        <div style="margin-top: 15px;">
          <el-radio-group v-model="chartType" @change="chartTypeChange">
            <el-radio-button
              :disabled="!isClickBtn"
              v-for="item in radioGroups"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-radio-group>
        </div>
      </div>
    </LayoutIndex>
    <LayoutDetail>
      <div class="demoCharts">
        <BasicCharts 
          :option="option"
          :carouselNum="carouselNum" 
          v-if="showChart"
        />
        <div class="flex_center" v-else>
          <el-image
            style="width: 60%; height: 60%"
            :src="DataAnalytic"
            fit="fill"
          />
        </div>
      </div>
    </LayoutDetail>
  </div>
</template>

<script lang="ts" setup>
import DataAnalytic from '@/assets/images/home/DataAnalytic.png'
import { ref, watch } from 'vue';
import { ElMessageBox } from 'element-plus'
import dataSourceApi from '@/request/api/dataSource'
import { showMessageBox } from '../../utils/alertMsg';
import { radioGroups } from './data';

interface radioGroupsItem {
  label: string
  value: string
}

type chartT = 'All_clients_bandwidth_info' | 'All_clients_dataset_info' | 'All_clients_transmission_power_info' | 'G' | 'energy_harvesting' | 'f' | 'unit_cost';

let deviceNum = ref<number>(null);
// const radioGroups = ref<Array<radioGroupsItem>>([])
const chartType = ref<chartT>('All_clients_bandwidth_info');
const isClickBtn = ref<boolean>(false);
const showChart = ref<boolean>(false);

// 按钮组图像切换
const chartTypeChange = (val: any) => {
  // console.log(val)
}

// 帮我写一个算法，传入一个数组生成一个二维数组，其每一项都是原数组的每一项的数组，例如传入originArr:
const handleArr = (arr: Array<Array<number>>) => {
  const newArr = []
  const len = arr[0].length;
  for (let i = 0; i < len; i++) {
    const tempArr = []
    for (let j = 0; j < arr.length; j++) {
      tempArr.push(arr[j][i])
    }
    newArr.push(tempArr)
  }
  return newArr
}

// 当前有个数组arr, 根据步长distance，重构arr的每一项：
// 例如传入如上arr, distance：5; 意思每隔5个取一个平均值,平均数不做整数取值
// 预期输出：[[3, 8], [6, 16]]
const reconstructArray = (arr: Array<Array<number>>, distance: number) => {
  if(distance == 0) {
    return arr;
  }
  const result = [];
  for (let i = 0; i < arr.length; i++) {
    const subArr = [];
    for (let j = 0; j < arr[i].length; j += distance) {
      let sum = 0;
      let count = 0;
      for (let k = j; k < Math.min(j + distance, arr[i].length); k++) {
        sum += arr[i][k];
        count++;
      }
      subArr.push(sum / count);
    }
    result.push(subArr);
  }
  return result;
};

const carouselNum = ref<number>(0);
// 建立map映射关系，设备数量 => 返回值; 若重新请求相同设备数量的数据，则更新map
const deviceMap = new Map();
const generateData = async (): Promise<void> => {
  if(!deviceNum.value) {
    showMessageBox('error', '请输入设备数量');
    return;
  }
  ElMessageBox.confirm(
    '点击生成后，会刷新当前设备数据并且生成新设备数对应的数据，是否继续？',
    '温馨提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    isClickBtn.value = true;
    const res = await dataSourceApi.getTd3DataSourceByCount({ initNum: +deviceNum.value }) as any;
    deviceMap.set(deviceNum.value, res); // 存储数据
    chartType.value = 'All_clients_bandwidth_info';
    drawChartFn(chartType.value);
    showChart.value = true;
  }).catch(() => {
    // ElMessage({
    //   type: 'info',
    //   message: '取消操作',
    // })
    // isClickBtn.value = false;
    showMessageBox('info', '取消操作');
  })
}
// {
//   name: 'Email',
//   type: 'line',
//   data: [120, 132, 101, 134, 90, 230, 210]
// }

interface seriesDataItem {
  name: string
  type: string
  data: Array<number>
  smooth: boolean
}

const distance = 10;
function drawChartFn(newVal: any) {
  if(deviceMap.has(deviceNum.value)) {
    const data = deviceMap.get(deviceNum.value);
    const targetArr = data[newVal];
    const newArr = handleArr(targetArr);
    const averageNewArr = reconstructArray(newArr, distance);
    // 数据数组
    const tempSeriesArr = ref<Array<seriesDataItem>>([])
    // x轴坐标
    const xAxisData = ref<Array<string>>([]);
    // 每条折线名称
    const seriesNames = ref<Array<string>>([]);
    for(let i = 0; i < averageNewArr.length; i++) {
      let type = ''
      if(['f'].includes(newVal)) {
        type = 'bar';
      } else {
        type = 'line';
      }
      tempSeriesArr.value.push({
        name: `设备${i + 1}`,
        type: type,
        data: averageNewArr[i],
        smooth: true,
      })
      seriesNames.value.push(`设备${i + 1}`);
    }
    const ItemLen = averageNewArr[0].length;
    for(let j = 0; j < ItemLen; j++) {
      xAxisData.value.push(j * distance + '');
    }
    option.value.xAxis.data = xAxisData.value;
    option.value.legend.data = seriesNames.value;
    option.value.series = tempSeriesArr.value;
    // console.log('option.value', option.value)
    // carouselNum.value = option.value.series[0].data.length;
  }
  option.value.title.text = newVal;
  switch(newVal) {
    case 'All_clients_bandwidth_info':
      option.value.yAxis.name = 'B';
      option.value.xAxis.name = '轮次'
      break;
    case 'All_clients_dataset_info':
      option.value.yAxis.name = 'Hz';
      option.value.xAxis.name = '轮次'
      break;
    case'All_clients_transmission_power_info':
      option.value.yAxis.name = 'dBm';
      option.value.xAxis.name = '轮次'
      break;
    case 'energy_harvesting':
      option.value.yAxis.name = 'KJ';
      option.value.xAxis.name = '轮次'
      break;
    case 'unit_cost':
      option.value.yAxis.name = 'cycles/bit';
      option.value.xAxis.name = '轮次'
      break;
    case 'G':
      option.value.yAxis.name = 'dB';
      option.value.xAxis.name = '轮次'
      break;
    case 'f':
      option.value.yAxis.name = 'GHz';
      option.value.xAxis.name = '台'
      break;
  }
}


watch(() => chartType.value, (newVal: chartT) => {
  // if(deviceMap.has(deviceNum.value)) {
  //   const data = deviceMap.get(deviceNum.value);
  //   const targetArr = data[newVal];
  //   const newArr = handleArr(targetArr);
  //   const averageNewArr = reconstructArray(newArr, distance);
  //   // 数据数组
  //   const tempSeriesArr = ref<Array<seriesDataItem>>([])
  //   // x轴坐标
  //   const xAxisData = ref<Array<string>>([]);
  //   // 每条折线名称
  //   const seriesNames = ref<Array<string>>([]);
  //   for(let i = 0; i < averageNewArr.length; i++) {
  //     let type = ''
  //     if(['f'].includes(newVal)) {
  //       type = 'bar';
  //     } else {
  //       type = 'line';
  //     }
  //     tempSeriesArr.value.push({
  //       name: `设备${i + 1}`,
  //       type: type,
  //       data: averageNewArr[i],
  //       smooth: true,
  //     })
  //     seriesNames.value.push(`设备${i + 1}`);
  //   }
  //   const ItemLen = averageNewArr[0].length;
  //   for(let j = 0; j < ItemLen; j++) {
  //     xAxisData.value.push(j * distance + '');
  //   }
  //   option.value.xAxis.data = xAxisData.value;
  //   option.value.legend.data = seriesNames.value;
  //   option.value.series = tempSeriesArr.value;
  // }
  // option.value.title.text = newVal;
  // switch(newVal) {
  //   case 'All_clients_bandwidth_info':
  //     option.value.yAxis.name = 'B';
  //     option.value.xAxis.name = '轮次'
  //     break;
  //   case 'All_clients_dataset_info':
  //     option.value.yAxis.name = 'Hz';
  //     option.value.xAxis.name = '轮次'
  //     break;
  //   case'All_clients_transmission_power_info':
  //     option.value.yAxis.name = 'dBm';
  //     option.value.xAxis.name = '轮次'
  //     break;
  //   case 'energy_harvesting':
  //     option.value.yAxis.name = 'KJ';
  //     option.value.xAxis.name = '轮次'
  //     break;
  //   case 'unit_cost':
  //     option.value.yAxis.name = 'cycles/bit';
  //     option.value.xAxis.name = '轮次'
  //     break;
  //   case 'G':
  //     option.value.yAxis.name = 'dB';
  //     option.value.xAxis.name = '轮次'
  //     break;
  //   case 'f':
  //     option.value.yAxis.name = 'GHz';
  //     option.value.xAxis.name = '台'
  //     break;
  // }
  // console.log('watch')
  drawChartFn(newVal);
})

// 折线图
let option = ref<any>({
  title: {
    text: 'Stacked Line'
  },
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: [],
    textStyle: {
      color: '#000'
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    name: '轮次',
    type: 'category',
    boundaryGap: false,
    data: []
  },
  yAxis: {
    name: '',
    type: 'value'
  },
  series: []
});
</script>

<style lang="scss" scoped>
.demoCharts {
  height: 60vh;
}
</style>
